#include <iostream>
using namespace std;
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
    	if(pHead == nullptr)
    		return nullptr;
    	ListNode *p = pHead, *nt = pHead->next,*pre = nullptr;
    	// printList(pHead);
    	while(p && nt)
    	{
    		if(p->val != nt->val)
    		{
    			pre = p;
    			p = nt;
				nt = nt->next;
    		}
    		else
    		{
    			while(nt && p->val == nt->val)
    				nt = nt->next;
    			if(!pre)
    				pHead = nt;
    			else
    				pre ->next = nt;
    			while(p != nt)
    			{
    				ListNode *del = p;
    				p = p->next;
    				delete del;
    			}
    			if(nt)
    				nt = nt -> next;

    		}
    	}

    	return pHead;
    }
    void printList(ListNode *pHead)
    {
	    while(pHead)
		{
			cout<<pHead->val<<endl;
			pHead = pHead->next;
		}
    }
};

int main()
{
	Solution s;

	ListNode head(1),*p = &head;
	// s.printList(&head);
	int i = 2;
	p->next = new ListNode(i++);
	p = p->next;
	p->next = new ListNode(i);
	p = p->next;
	p->next = new ListNode(i++);
	p = p->next;
	p->next = new ListNode(i);
	p = p->next;
	p->next = new ListNode(i++);
	p = p->next;
	p->next = new ListNode(i++);
	s.printList(&head);
	s.deleteDuplication(&head);
	p = &head;
	s.printList(&head);
	return 0;
}